package com.engine.workflow.zhlx.web;

import com.alibaba.fastjson.JSONArray;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.webservices.WorkflowServiceImpl;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dusongsong
 * @date 2023年05月12日 14:20
 */
public class WfUtil extends BaseBean {

    /**
     * 校验workflowId
     *
     * @param workflowId
     * @return
     */
    public Map<String, Object> checkReqParams(String workflowId, String requestName, String mainData, String isnextFlow, String workcode) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        writeLog(">>>>>checkReqParams>>>workflowId=" + workflowId);
        writeLog(">>>>>checkReqParams>>>requestName=" + requestName);
        writeLog(">>>>>checkReqParams>>>mainData=" + mainData);
        writeLog(">>>>>checkReqParams>>>isnextFlow=" + isnextFlow);
        String code = "SUCCESS";
        String message = "";
        if ("".equals(workflowId.trim())) {
            code = "PARAM_ERROR";
            message += "workflowId参数必填;";
        }
        if ("".equals(Util.null2String(requestName))) {
            code = "PARAM_ERROR";
            message += "requestName参数必填;";
        }
        if ("".equals(Util.null2String(mainData))) {
            code = "PARAM_ERROR";
            message += "mainData参数必填;";
        }
        if ("".equals(Util.null2String(isnextFlow))) {
            code = "PARAM_ERROR";
            message += "isnextFlow参数必填;";
        }
        if ("".equals(Util.null2String(workcode))) {
            code = "PARAM_ERROR";
            message += "workcode参数必填;";
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 校验workflowId
     *
     * @param workflowId
     * @return
     */
    public Map<String, Object> checkReqParams1(String requestId, String workflowId, String isLeave) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        writeLog(">>>>>checkReqParams>>>requestId=" + requestId);
        writeLog(">>>>>checkReqParams>>>workflowId=" + workflowId);
        writeLog(">>>>>checkReqParams>>>isLeave=" + isLeave);
        String code = "SUCCESS";
        String message = "";
        if ("".equals(workflowId.trim())) {
            code = "PARAM_ERROR";
            message += "requestId参数必填;";
        }
        if ("".equals(Util.null2String(workflowId))) {
            code = "PARAM_ERROR";
            message += "workflowId参数必填;";
        }
        if ("".equals(Util.null2String(isLeave))) {
            code = "PARAM_ERROR";
            message += "isLeave参数必填;";
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 提交流程
     */
    public String submitWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.submitWorkflowRequest(null, requestid, userid, "submit", "由外部调用提交完成");
    }

    /**
     * 删除流程
     */
    public boolean deleteWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.deleteRequest(Util.getIntValue(requestid), Util.getIntValue(userid));
    }

    /**
     * @param @param  creatorId    创建人Id
     * @param @param  workflowId   流程Id
     * @param @param  requestName  请求标题
     * @param @param  IsNextFlow   是否提交到下一节点
     * @param @param  requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: WorkflowCreateByMainTableMap
     */
    public String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, Object> requestMainMap) {
        writeLog("-----创建流程传递的参数个数--------");
        writeLog("creatorId:" + creatorId);
        writeLog("workflowId:" + workflowId);
        writeLog("requestName:" + requestName);
        writeLog("IsNextFlow:" + IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if ("0".equals(IsNextFlow)) {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, Object> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue());
            p++;
        }
        writeLog("-----创建流程传递的参数个数p=" + p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                writeLog("=======" + e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:" + requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            writeLog(sbf.toString());
            System.out.println("" + sbf.toString());
        } catch (Exception e) {
            writeLog("错误：" + e);
            System.out.println("错误：" + e);
        }
        return requestid;
    }

    /**
     * 更新明细表单信息
     */
    public boolean updateDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>updateDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 获取表单ID
     */
    public String getFormid(String workflowid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select abs(formid) from workflow_base where id=?", workflowid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 获取明细主键ID
     */
    public String getIdByRequestId(String workflowid, String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select abs(formid) from  workflow_base where id=?", workflowid);
        rs.next();
        String tableName = "formtable_main_" + Util.null2String(rs.getString(1));
        rs.executeQuery("select id from " + tableName + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 获取人员ID
     */
    public String getResourceid(String workcode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from  hrmresource where workcode=?", workcode);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    public  boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }
}
